package com.apkfuns.jsbridge.view.slice;

import com.apkfuns.jsbridge.JsBridge;
import com.apkfuns.jsbridge.LogUtils;
import com.apkfuns.jsbridge.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.webengine.*;
import ohos.agp.utils.TextTool;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import java.io.IOException;
import java.net.URLConnection;

public class WebViewAbilitySlice extends AbilitySlice {
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00202, "WebViewAbilitySlice");

    private JsBridge jsBridge;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_web_view);

        jsBridge = JsBridge.loadModule();

        WebView webView = (WebView) findComponentById(ResourceTable.Id_webview);
        webView.getWebConfig().setJavaScriptPermit(true);  // 如果网页需要使用JavaScript，增加此行；如何使用JavaScript下文有详细介绍



        String url =  intent.getStringParam("url");
        if (TextTool.isNullOrEmpty(url)) {
            //url = "https://example.com/rawfile/index.html";
            webView.load(getString(ResourceTable.String_system_webview_url));
        } else {

            webView.load(url);
        }


        webView.setBrowserAgent(new BrowserAgent(this) {

            @Override
            public boolean onJsMessageShow(WebView webView, String url, String message, boolean isAlert, JsMessageResult result) {
                LogUtils.info("WebViewAbilitySlice","JACK onJsMessageShow2 " + message);
                return super.onJsMessageShow(webView, url,message,isAlert,result);
            }

            @Override
            public boolean onJsTextInput(WebView webView, String url, String message, String defaultInput, JsTextInputResult result) {
                LogUtils.info("WebViewAbilitySlice","JACK onJsTextInput2 " + message);
                if (jsBridge.callJsPrompt(message, result)) {
                    return true;
                }
                return super.onJsTextInput(webView, url, message, defaultInput, result);
            }

        });

        webView.setWebAgent(new JsWebAgent());


    }


    @Override
    public void terminateAbility() {
        jsBridge.release();
        super.terminateAbility();

    }


    class JsWebAgent extends WebAgent{
        @Override
        public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
            final String authority = "example.com";
            final String rawFile = "/rawfile/";
            Uri requestUri = request.getRequestUrl();
            if (authority.equals(requestUri.getDecodedAuthority())) {
                String path = requestUri.getDecodedPath();
                if (TextTool.isNullOrEmpty(path)) {
                    return super.processResourceRequest(webView, request);
                }
                if (path.startsWith(rawFile)) {
                    // 根据自定义规则访问资源文件
                    String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
                    String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                    try {
                        Resource resource = getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                        return new ResourceResponse(mimeType, resource, null);
                    } catch (IOException e) {
                        HiLog.info(LABEL, "open raw file failed");
                    }
                }
            }
            return super.processResourceRequest(webView, request);
        }

        @Override
        public void onPageLoaded(WebView webView, String url) {
            super.onPageLoaded(webView, url);
            // 页面加载结束后自定义处理
            jsBridge.injectJs(getAbility(),webView);
        }

        @Override
        public void onLoadingContent(WebView webView, String url) {
            super.onLoadingContent(webView, url);
            // 加载资源时自定义处理
        }

        @Override
        public void onError(WebView webView, ResourceRequest request, ResourceError error) {
            super.onError(webView, request, error);
            // 发生错误时自定义处理
        }
    }

}
